package cn.tcpTask;

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import cn.tcp.TcpNewUtil;

public class SwitchTask extends TimerTask {
	private static Timer timer;
	private int decid;
	private int switchid;
	private long delay;
	private boolean writeValue;
	private String host;
	private boolean flag = true;

	/**
	 * 
	 * @param host
	 *            主机
	 * @param deviceID
	 *            节点ID
	 * @param switchID
	 *            开关通道ID
	 * @param wirteValue
	 *            写入值
	 * @param delay
	 *            多久后开始执行。
	 */
	public SwitchTask(String host, int deviceID, int switchID,
			boolean wirteValue, long delay) {
		this.decid = deviceID;
		this.switchid = switchID;
		this.delay = delay;
		this.host = "192.168.1.122";
		this.writeValue = wirteValue;
	}


	public boolean startSwitchTask() {
		try {
			long beforeTime=System.currentTimeMillis();
			timer = new Timer(false);
			SwitchTask mt = new SwitchTask(host, decid, switchid, writeValue,delay);
			timer.schedule(mt, delay);
			while (mt.isFlag()) {
				Thread.sleep(delay + 100);
				if(mt.isFlag()){
					System.out.println("任务正在执行，请稍后！");
				}else{
					long afterTime=(System.currentTimeMillis()-beforeTime)/1000;
					timer.cancel();
					System.out.println("任务已经成功执行！共花费："+afterTime+" seconds");
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void run() {
		 
		TcpNewUtil tnu=new TcpNewUtil();
		tnu.ControlSwitch(decid, switchid, writeValue);
		//运行完之后  恢复标志位
		flag = false;
	}

	public boolean isFlag() {
		return flag;
	}
}
